package com.hqd.jjvm.classpath;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 加载路径下的class文件
 *
 * @author hqd
 */
public class DirClassResource extends AbstractClassResource {

    public DirClassResource(String rootPath) {
        super(rootPath, CLASS_FILE_SUFFIX);
    }

    @Override
    protected void init() {
        setClassFileList(searchFiles(getRootPath(), CLASS_FILE_SUFFIX, true));
    }

    @Override
    public List<ClassFileInfo> readAllClass() throws IOException {
        for (File file : getClassFileList()) {
            ClassFileInfo classFileInfo = new ClassFileInfo(readClassFileToStr(new FileInputStream(file)), getRootPath(), file.getName());
            getClassHexMap().put(file.getPath(), classFileInfo);
        }
        return new ArrayList<>(getClassHexMap().values());
    }

    @Override
    public ClassFileInfo readClass(String filePath) throws IOException {
        File classFile = new File((getRootPath() + "/" + filePath).intern());
        ClassFileInfo classFileInfo = null;
        if (classFile.isFile() && classFile.getName().endsWith(CLASS_FILE_SUFFIX)) {
            if (getClassHexMap().get(classFile.getPath()) == null) {
                classFileInfo = new ClassFileInfo(readClassFileToStr(new FileInputStream(classFile)), filePath, classFile.getPath(), classFile.getName());
                getClassHexMap().put(classFile.getPath(), classFileInfo);
            }
            classFileInfo = getClassHexMap().get(classFile.getPath());
        }
        return classFileInfo;
    }

    @Override
    public boolean isExists(String classPath) {
        return new File(getRootPath() + "/" + classPath).exists();
    }
}
